<template>
  <div class="page-miH page-bgBack ">
    <a-alert type="error" banner style="margin-top:16px" v-if="payStatus === 4 && pageState && approvalRecord.errorNumber > 0">
      <div slot="description" style="display:flex;justify-content:space-between;">
        <div style="margin-left:32px">
          有{{ approvalRecord && approvalRecord.errorNumber }}人薪资发放异常，总金额¥{{ approvalRecord.errorMoney }}，请尽快处理
        </div>
        <div style="color:#FF7085;cursor:pointer" @click="importErrData">导出错误数据</div>
      </div>
    </a-alert>
    <TableBody
      style="margin-top:16px"
      tableName="prePersonnel"
      :source="dataList"
      :headerRowID="'sortable_list'"
      :columns="columns"
      @onReload="getTransferAccountsDetails"
      @onExportAll="exportFile"
    >
      <template slot="search">
        <a-input-search allow-clear placeholder="搜索姓名/手机号/身份证号" style="width: 225px" @search="inputChange" />
      </template>
      <template slot="search-right">
        <a-button
          :disabled="!selectedRowKeys || !selectedRowKeys.length"
          v-if="(pageState && payStatus === 4) || (pageState && payStatus === 6)"
          @click="batchToAbnormal"
          ><a-icon type="profile" />批量处理</a-button
        >
      </template>
      <template slot-scope="prop">
        <a-table
          v-if="(pageState && payStatus === 4) || (pageState && payStatus === 6)"
          :class="prop.className"
          :components="prop.components"
          :columns="prop.columns"
          :scroll="{ x: prop.scrollWidth }"
          :customHeaderRow="
            () => {
              return {
                domProps: {
                  id: prop.headerRowID
                }
              };
            }
          "
          :loading="loading"
          rowKey="id"
          :data-source="dataList"
          :pagination="pagination"
          @change="handleTableChange"
          :row-selection="{
            selectedRowKeys: selectedRowKeys,
            onChange: onSelectChange,
            getCheckboxProps: record => ({
              props: {
                disabled: record.isDispose === null // Column configuration not to be checked
              }
            })
          }"
        >
          <a slot="channelName" slot-scope="text" style="cursor:text;color:#595959">{{ text ? `￥${text}` : "" }}</a>
          <span slot="gmtCreate" slot-scope="text">{{ moment(text).format("YYYY-MM-DD HH:mm") }}</span>
          <span slot="payTime" slot-scope="text">{{ moment(text).format("YYYY-MM-DD HH:mm") }}</span>
          <div slot="isDispose" slot-scope="text">
            <div v-if="text === false">
              <div class="statusp" style="background:#FF7085"></div>
              未处理
            </div>
            <div v-if="text === true">
              <div class="statusp" style="background:#32CCAA "></div>
              已处理
            </div>
            <div v-if="text === null">
              <div class="statusp" style="background:#F79300"></div>
              发放成功
            </div>
          </div>
          <!-- v-if="record.isDispose === 1 || record.isDispose === 0" -->
          <div slot="action" slot-scope="text, record">
            <a-button :disabled="record.isDispose === null" type="link" @click="toAbnormal(record)">处理</a-button>
          </div>
        </a-table>
        <a-table
          v-else
          :class="prop.className"
          :components="prop.components"
          :columns="prop.columns"
          :scroll="{ x: prop.scrollWidth }"
          :customHeaderRow="
            () => {
              return {
                domProps: {
                  id: prop.headerRowID
                }
              };
            }
          "
          :loading="loading"
          rowKey="id"
          :data-source="dataList"
          :pagination="pagination"
          @change="handleTableChange"
        >
          <a slot="channelName" slot-scope="text" style="cursor:text;color:#595959">{{ text ? `￥${text}` : "" }}</a>
          <span slot="gmtCreate" slot-scope="text">{{ moment(text).format("YYYY-MM-DD HH:mm") }}</span>
          <span slot="payTime" slot-scope="text">{{ moment(text).format("YYYY-MM-DD HH:mm") }}</span>
        </a-table>
      </template>
    </TableBody>
    <a-modal v-model="batchVisible" title="处理异常" @ok="handleBatchOk">
      <div v-if="selectedEmp.length < 4" style="font-size:14px;font-weight:400;color:#767885;">
        已选择：<span v-for="(item, index) in selectedEmp" :key="index">{{ item.name }},</span>
      </div>
      <div v-else style="font-size:14px;font-weight:400;color:#767885;">
        已选择：{{ selectedEmp[0].name + "," + selectedEmp[1].name + "," + selectedEmp[2].name + "等人" }}
      </div>
      <div style="font-size: 12px;font-weight: 400;color: #767885;margin-top:12px"></div>
      <div style="font-size: 14px;font-weight: 400;color: #767885;margin-top:24px">
        状态：<a-radio-group name="radioGroup" v-model="batchisDispose">
          <a-radio :value="true">
            已处理
          </a-radio>
          <a-radio :value="false">
            异常
          </a-radio>
        </a-radio-group>
      </div>
      <div style="font-size: 14px;font-weight: 400;color: #767885;margin-top:24px;display:flex">
        <div>
          备注：
        </div>
        <a-textarea style="width:430px" v-model="batchremark" placeholder="请填写备注" />
      </div>
    </a-modal>
    <a-modal v-model="visible" title="处理异常" @ok="handleOk">
      <div style="font-size:18px;font-weight: 500;color:#3C3D43;">
        {{ abnormalItem.name }}
      </div>
      <div style="font-size: 12px;font-weight: 400;color: #767885;margin-top:12px">身份证号：{{ abnormalItem.idCard }}</div>
      <div style="font-size: 14px;font-weight: 400;color: #767885;margin-top:24px">
        状态：<a-radio-group name="radioGroup" v-model="abnormalItem.isDispose">
          <a-radio :value="true">
            已处理
          </a-radio>
          <a-radio :value="false">
            异常
          </a-radio>
        </a-radio-group>
      </div>
      <div style="font-size: 14px;font-weight: 400;color: #767885;margin-top:24px;display:flex">
        <div>
          备注：
        </div>
        <a-textarea style="width:430px" v-model="abnormalItem.remark" placeholder="请填写备注" />
      </div>
    </a-modal>
  </div>
</template>

<script>
import { transferAccountsDetails, editAccountsDetails, batchAccountsDetails, batchAccountsDetails2 } from "../api";
import axios from "axios";
import qs from "qs";
import ExportMixin from "xqjr-plugin-common/UploadOrExport/exportMixin";
const mixin = new ExportMixin();
export default {
  data() {
    return {
      mixin,
      columns: [
        {
          title: "姓名",
          dataIndex: "name",
          key: "name",
          colDefault: true,
          width: 150
        },
        {
          title: "身份证号",
          dataIndex: "idCard",
          key: "idCard",
          colDefault: true,
          width: 180
        },
        {
          title: "手机号码",
          dataIndex: "phone",
          key: "phone",
          colDefault: true,
          width: 120
        },
        {
          title: "薪资",
          dataIndex: "money",
          key: "money",
          colDefault: true,
          scopedSlots: { customRender: "channelName" },
          width: 100
        }
      ],
      columnsCopy: [
        {
          title: "姓名",
          dataIndex: "name",
          key: "name",
          colDefault: true,
          width: 150
        },
        {
          title: "身份证号",
          dataIndex: "idCard",
          key: "idCard",
          colDefault: true,
          width: 180
        },
        {
          title: "手机号码",
          dataIndex: "phone",
          key: "phone",
          colDefault: true,
          width: 120
        },
        {
          title: "薪资",
          dataIndex: "money",
          key: "money",
          colDefault: true,
          scopedSlots: { customRender: "channelName" },
          width: 100
        }
      ],
      dataList: [],
      visible: false,
      loading: false,
      abnormalItem: {},
      rowSelection: undefined,
      batchVisible: false,
      batchremark: undefined,
      batchisDispose: null,
      selectedRowKeys: [],
      selectedEmp: [],
      params: {},
      pagination: {
        pageSize: 10,
        total: 0,
        size: "default",
        current: 1,
        showTotal: total => `共 ${total} 条`,
        showQuickJumper: true,

        showSizeChanger: true,
        personalPeriod: null,
        editCompanyName: null,
        ticketRecord: null,
        receivableRecord: null,
        pageSizeOptions: ["10", "20", "50", "100"]
      }
    };
  },
  props: {
    approvalRecord: {
      type: Object,
      default: () => {}
    },
    pageState: { type: Boolean, default: false },
    payStatus: { type: Number, default: 1 }
  },
  watch: {
    approvalRecord: {
      handler(newVal) {
        this.getTransferAccountsDetails();
        this.updateDetail();
      },
      immediate: true
    }
  },
  created() {
    this.updateDetail();
    // this.rowSelection =
    //   this.pageState && this.payStatus === 4
    //     ? {
    //         selectedRowKeys: this.selectedRowKeys,
    //         onChange: this.onSelectChange()
    //       }
    //     : undefined;
  },
  methods: {
    updateDetail() {
      this.columns = JSON.parse(JSON.stringify(this.columnsCopy));
      if (this.approvalRecord && this.approvalRecord.type === 1) {
        this.columns.splice(3, 0, {
          title: "发放账号",
          dataIndex: "identity",
          key: "identity",
          colDefault: true,
          width: 150
        });
      }
      if (this.approvalRecord && this.approvalRecord.type === 3) {
        this.columns.splice(
          2,
          1,
          {
            title: "银行卡号",
            dataIndex: "identity",
            key: "identity",
            colDefault: true,
            width: 150
          },
          {
            title: "银行名称",
            dataIndex: "bankName",
            key: "bankName",
            colDefault: true,
            width: 150
          }
        );
      }
      if (this.approvalRecord && this.approvalRecord.type === 3 && (this.payStatus === 2 || this.payStatus === 4 || this.payStatus === 6)) {
        this.columns.push({
          title: "手续费",
          dataIndex: "fee",
          key: "fee",
          colDefault: true,
          width: 120
        });
      }
      if (this.pageState && this.payStatus === 2) {
        this.columns.splice(
          this.columns.length - 2,
          0,
          {
            title: "单笔交易流水号",
            dataIndex: "thirdPartyInteriorDetailId",
            key: "thirdPartyInteriorDetailId",
            colDefault: true,
            width: 300
          },
          {
            title: "发放完成时间",
            dataIndex: "payTime",
            key: "payTime",
            colDefault: true,
            scopedSlots: { customRender: "payTime" },
            width: 120
          }
        );
      }
      if ((this.pageState && this.payStatus === 4) || (this.pageState && this.payStatus === 6)) {
        this.columns.splice(
          this.columns.length,
          0,
          {
            title: "单笔交易流水号",
            dataIndex: "thirdPartyInteriorDetailId",
            key: "thirdPartyInteriorDetailId",
            colDefault: true,
            width: 300
          },
          {
            title: "异常原因",
            dataIndex: "failCause",
            key: "failCause",
            colDefault: true,
            width: 120
          },
          {
            title: "处理状态",
            dataIndex: "isDispose",
            key: "isDispose",
            colDefault: true,
            scopedSlots: { customRender: "isDispose" },
            width: 100
          },
          {
            title: "备注",
            dataIndex: "remark",
            key: "remark",
            colDefault: true,
            width: 120
          },

          { title: "操作", dataIndex: "action", key: "action", colDefault: true, scopedSlots: { customRender: "action" }, width: 100 }
        );
      }
    },
    importErrData() {
      this.params = {
        isDispose: false,
        batchId: this.approvalRecord.id
      };
      this.url = `/hr/api/v1/transferAccountsDetails/selectExportErrorList`;
      this.excelName = "错误数据导出详情.xlsx";
      this.getDownload2();
    },
    getDownload2() {
      const token = this.$store.state.auth.token;
      axios({
        url: this.url,
        params: this.params,
        paramsSerializer: param => {
          return qs.stringify(param, { indices: false });
        },
        method: "get",
        responseType: "blob",
        headers: {
          token: token
        }
      })
        .then(res => {
          const link = document.createElement("a");
          const blob = new Blob([res.data], {
            type: "application/vnd.ms-excel"
          });
          link.style.display = "none";
          link.href = URL.createObjectURL(blob);
          link.setAttribute("download", this.excelName);
          document.body.appendChild(link);
          link.click();
          document.body.removeChild(link);
        })
        .catch(err => {
          console.log("debug log --> ", err);
        });
    },
    handleBatchOk() {
      batchAccountsDetails2({
        ids: this.selectedRowKeys,
        isDispose: this.batchisDispose,
        remark: this.batchremark,
        batchId: this.approvalRecord.id,
        id: "1"
      }).then(res => {
        this.batchVisible = false;
        this.$notification.success({
          message: "处理成功"
        });
        this.selectedRowKeys = [];
        this.$emit("pageRefresh");

        this.getTransferAccountsDetails();
      });
    },
    batchToAbnormal() {
      this.batchVisible = true;
      this.batchremark = undefined;
      this.batchisDispose = null;
    },
    onSelectChange(selectedRowKeys, e) {
      this.selectedRowKeys = selectedRowKeys;
      this.selectedEmp = JSON.parse(JSON.stringify(e));
      console.log(this.selectedEmp);
    },
    handleOk() {
      var arr = [];
      arr.push(this.abnormalItem.id);
      batchAccountsDetails2({
        ids: arr,
        isDispose: this.abnormalItem.isDispose,
        remark: this.abnormalItem.remark,
        batchId: this.approvalRecord.id,
        id: "1"
      }).then(res => {
        this.visible = false;
        this.$notification.success({
          message: "处理成功"
        });

        this.$emit("pageRefresh");

        this.getTransferAccountsDetails();
      });
    },
    toAbnormal(record) {
      this.abnormalItem = JSON.parse(JSON.stringify(record));
      this.visible = true;
    },
    inputChange(e) {
      this.name = e;
      this.pagination.current = 1;
      this.getTransferAccountsDetails();
    },
    // 分页器
    handleTableChange(pagination, filters, sorter) {
      this.pagination.current = pagination.current;
      this.pagination.pageSize = pagination.pageSize;
      this.getTransferAccountsDetails();
    },
    exportFile() {
      console.log(this.columns);
      this.params2 = {
        batchId: this.approvalRecord.id,
        name: this.name,
        exportColumns: this.columns.map(z => {
          return {
            title: z.title,
            dateFormat: z.title === "发放完成时间" ? "yyyy-MM-dd HH:mm" : "yyyy-MM-dd",
            dataIndex: z.dataIndex
          };
        })
      };
      this.url = `/hr/api/v1/transferAccountsDetails/export`;
      this.excelName = `转账批次明细.xlsx`;
      this.getDownload();
    },
    getDownload() {
      const token = this.$store.state.auth.token;
      axios({
        url: this.url,
        data: this.params2,
        paramsSerializer: param => {
          return qs.stringify(param, { indices: false });
        },
        method: "post",
        responseType: "blob",
        headers: {
          token: token
        }
      })
        .then(res => {
          const link = document.createElement("a");
          const blob = new Blob([res.data], {
            type: "application/vnd.ms-excel"
          });
          link.style.display = "none";
          link.href = URL.createObjectURL(blob);
          link.setAttribute("download", this.excelName);
          document.body.appendChild(link);
          link.click();
          document.body.removeChild(link);
        })
        .catch(err => {
          console.log("debug log --> ", err);
        });
    },
    getTransferAccountsDetails() {
      const data = {
        pageNo: this.pagination.current,
        pageSize: this.pagination.pageSize,
        batchId: this.approvalRecord.id,
        name: this.name
      };
      this.loading = true;
      transferAccountsDetails(data)
        .then(res => {
          this.loading = false;
          this.dataList = res.data.entities;
          this.pagination.total = res.data && res.data.entityCount;
        })
        .catch(err => {
          this.loading = false;
          console.log(err);
        });
    }
  }
};
</script>

<style lang="scss" scoped>
::v-deep.ant-alert-with-description {
  padding: 8px;
}
::v-deep.ant-alert-description {
  margin-left: 28px;
}
::v-deep.ant-alert-with-description .ant-alert-icon {
  font-size: 14px;
  left: 16px;
}
.statusp {
  display: inline-block;
  width: 6px;
  height: 6px;
  border-radius: 50%;
}
</style>
